package leetcode_501_600;

import sun.security.provider.Sun;

import java.util.*;

public class LeeCode_599 {
    public static void main(String[] args) {

    }
    private static String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> m1 = new HashMap<>();
        for (int i = 0; i < list1.length; i++) {
            if (!m1.containsKey(list1[i])){
                m1.put(list1[i], i);
            }
        }
        TreeMap<Integer, List<String>> tree = new TreeMap<>();
        for (int i = 0; i < list2.length; i++) {
            if (m1.containsKey(list2[i])){
                int sum = m1.get(list2[i]) + i;
                if (tree.isEmpty()){
                    List<String> list = new ArrayList<>();
                    list.add(list2[i]);
                    tree.put(sum, list);
                }else {
                    if (tree.firstKey() > sum){
                        tree.pollFirstEntry();
                        List<String> list = new ArrayList<>();
                        list.add(list2[i]);
                        tree.put(sum, list);
                    }else if (sum == tree.firstKey()){
                        tree.get(tree.firstKey()).add(list2[i]);
                    }
                }
            }
        }
        List<String> list = tree.get(tree.firstKey());
        String[] ans = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ans[i] = list.get(i);
        }
        return ans;
    }
}
